package com.hnluchuan.staff.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;
import org.apache.commons.lang3.StringUtils;
	
import com.hnluchuan.core.dao.BaseDAO;
import com.hnluchuan.staff.model.News;
import com.hnluchuan.staff.dto.NewsDTO;
import com.hnluchuan.core.support.Page;

@Repository
public class NewsDAO extends BaseDAO<News> {

    public List<News> find(NewsDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From News n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (StringUtils.isNotBlank(dto.getSerialNum())) {
            hql.append(" and n.serialNum = ? ");
            paras.add(dto.getSerialNum());
        }		
        if (dto.getStatus() != null) {
            hql.append(" and n.status = ? ");
            paras.add(dto.getStatus());
        }
        if (StringUtils.isNotBlank(dto.getTitle())) {
            hql.append(" and n.title like ? ");
            paras.add("%" + dto.getTitle() + "%");
        }					
        hql.append(" order by n.id desc ");
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public News findOne(NewsDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<News> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }
    
    @Override
	public Long create(News news) {
	    if (news.getCreator() == null) {     
	        // news.setCreator(getCurrentUser());
	    }        
	    if (news.getCreateTime() == null) {     
	        news.setCreateTime(new Date());
	    }    
	    if (news.getUpdator() == null) {     
	        // news.setUpdator(getCurrentUser());
	    }        
	    if (news.getUpdateTime() == null) {     
	        news.setUpdateTime(new Date());
	    }    
		return super.create(news);
	}

	@Override
	public void update(News news) {
	    if (news.getUpdator() == null) {     
	        // news.setUpdator(getCurrentUser());
	    }        
	    if (news.getUpdateTime() == null) {     
	        news.setUpdateTime(new Date());
	    }    
		super.update(news);
	}
    
}
